package roleService

import (
	roleDto "news_for_deepseek_interface/dto/admin/system/role"
	"news_for_deepseek_interface/model"
	adminModel "news_for_deepseek_interface/model/admin"

	"gorm.io/gorm"
)

func UpdateUserRole(params roleDto.UpdateUserRoleRequest) error {
	db := model.GetInstance().GetDB()

	// 开启事务
	return db.Transaction(func(tx *gorm.DB) error {
		// 先删除原有的角色关联
		if err := tx.Where("admin_id = ?", params.AdminId).
			Delete(&adminModel.AdminWithGroupStruct{}).Error; err != nil {
			return err
		}

		// 添加新的角色关联
		for _, roleId := range params.Roles {
			adminWithGroup := adminModel.AdminWithGroupStruct{
				AdminId:      params.AdminId,
				AdminGroupId: roleId,
			}
			if err := tx.Create(&adminWithGroup).Error; err != nil {
				return err
			}
		}

		return nil
	})
}
